package com.example.demo03_mvm.http;

import android.text.TextUtils;

import com.example.demo03_mvm.App;
import com.example.demo03_mvm.utils.ACache;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtils {
    private RetrofitUtils(){}
    private static RetrofitUtils retrofitUtils;
    private ApiService api;
    public synchronized static RetrofitUtils getRetrofitUtils(){
        if(retrofitUtils==null){
            retrofitUtils=new RetrofitUtils();
        }
        return retrofitUtils;
    }

    private Retrofit retrofit;
    public ApiService initRetrofit(){
        if(retrofit==null){
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request.Builder builder = chain.request().newBuilder();
                            String token = ACache.get(App.getContext()).getAsString("token");
                            if(!TextUtils.isEmpty(token)){
                                builder.addHeader("token",token);
                            }
                            Request request = builder.build();
                            return chain.proceed(request);
                        }
                    })
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                    .build();

            retrofit=new Retrofit.Builder().baseUrl("http://43.143.146.165:8181/")
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())//gson
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//rxjava
                    .build();
        }
        api=retrofit.create(ApiService.class);
        return api;
    }
}
